<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;

class ConvertEmptyStringsToNull
{
    protected $empty_value;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $agent = $request->server('User-Agent');

        $this->empty_value = Str::contains($agent, 'iPhone') ? '' : null;

        if ($response instanceof JsonResponse) {
            $data = $this->clean($response->getData(true));

            $response->setData($data);
        }
        
        return $response;
    }

    protected function transform($key, $value)
    {
        return is_string($value) && $value === '' ? $this->empty_value : $value;
    }

    protected function clean(array $data)
    {
        return collect($data)->map(function ($value, $key) {
            return $this->cleanValue($key, $value);
        })->all();
    }

    protected function cleanValue($key, $value)
    {
        if (is_array($value)) {
            if (empty($value)) {
                return $this->empty_value;
            }

            return $this->clean($value);
        }

        return $this->transform($key, $value);
    }
}
